package com.expert.miniapp.controller;

import com.expert.miniapp.dto.ResultDTO;
import com.expert.miniapp.dto.UpdateProfileRequest;
import com.expert.miniapp.dto.UserDTO;
import com.expert.miniapp.service.OSSService;
import com.expert.miniapp.service.UserService;
import com.expert.miniapp.util.JwtUtil;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * UserController - 用户控制器
 * 提供用户信息管理相关接口
 *
 * @author System
 * @since 2025-01-14
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private OSSService ossService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 上传用户头像
     *
     * @param file 头像文件
     * @param authorization Authorization Header（Bearer token）
     * @return 头像URL
     */
    @PostMapping(value = "/avatar", produces = "application/json;charset=UTF-8")
    public ResultDTO<Map<String, String>> uploadAvatar(
            @RequestParam("file") MultipartFile file,
            @RequestHeader("Authorization") String authorization
    ) {
        logger.info("接收到头像上传请求: filename={}, size={}", file.getOriginalFilename(), file.getSize());

        try {
            // 从Token中获取userId
            String token = extractToken(authorization);
            String userId = jwtUtil.getUserIdFromToken(token);

            if (userId == null) {
                return ResultDTO.error("Token无效或已过期");
            }

            // 上传到OSS
            String avatarUrl = ossService.uploadAvatar(file, userId);

            Map<String, String> result = new HashMap<>();
            result.put("avatarUrl", avatarUrl);

            logger.info("头像上传成功: userId={}, url={}", userId, avatarUrl);
            return ResultDTO.success(result);

        } catch (Exception e) {
            logger.error("头像上传失败", e);
            return ResultDTO.error("头像上传失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     *
     * @param request 更新请求
     * @param authorization Authorization Header（Bearer token）
     * @return 更新后的用户信息
     */
    @PutMapping(value = "/profile", produces = "application/json;charset=UTF-8")
    public ResultDTO<UserDTO> updateProfile(
            @Valid @RequestBody UpdateProfileRequest request,
            @RequestHeader("Authorization") String authorization
    ) {
        logger.info("接收到更新用户信息请求");

        try {
            // 从Token中获取userId
            String token = extractToken(authorization);
            String userId = jwtUtil.getUserIdFromToken(token);

            if (userId == null) {
                return ResultDTO.error("Token无效或已过期");
            }

            // 更新用户信息
            UserDTO userDTO = userService.updateProfile(userId, request);

            logger.info("用户信息更新成功: userId={}", userId);
            return ResultDTO.success(userDTO);

        } catch (Exception e) {
            logger.error("更新用户信息失败", e);
            return ResultDTO.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     *
     * @param authorization Authorization Header（Bearer token）
     * @return 用户信息
     */
    @GetMapping(value = "/profile", produces = "application/json;charset=UTF-8")
    public ResultDTO<UserDTO> getProfile(@RequestHeader("Authorization") String authorization) {
        logger.info("接收到获取用户信息请求");

        try {
            // 从Token中获取userId
            String token = extractToken(authorization);
            String userId = jwtUtil.getUserIdFromToken(token);

            if (userId == null) {
                return ResultDTO.error("Token无效或已过期");
            }

            // 查询用户信息
            UserDTO userDTO = userService.getUserById(userId);

            if (userDTO == null) {
                return ResultDTO.error("用户不存在");
            }

            logger.info("查询用户信息成功: userId={}", userId);
            return ResultDTO.success(userDTO);

        } catch (Exception e) {
            logger.error("查询用户信息失败", e);
            return ResultDTO.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据用户ID查询用户信息（可选接口）
     *
     * @param userId 用户ID
     * @param authorization Authorization Header（Bearer token）
     * @return 用户信息
     */
    @GetMapping(value = "/{userId}", produces = "application/json;charset=UTF-8")
    public ResultDTO<UserDTO> getUserById(
            @PathVariable String userId,
            @RequestHeader("Authorization") String authorization
    ) {
        logger.info("接收到查询用户信息请求: targetUserId={}", userId);

        try {
            // 验证Token
            String token = extractToken(authorization);
            if (!jwtUtil.validateToken(token)) {
                return ResultDTO.error("Token无效或已过期");
            }

            // 查询用户信息
            UserDTO userDTO = userService.getUserById(userId);

            if (userDTO == null) {
                return ResultDTO.error("用户不存在");
            }

            logger.info("查询用户信息成功: userId={}", userId);
            return ResultDTO.success(userDTO);

        } catch (Exception e) {
            logger.error("查询用户信息失败", e);
            return ResultDTO.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 从Authorization Header中提取Token
     */
    private String extractToken(String authorization) {
        if (authorization != null && authorization.startsWith("Bearer ")) {
            return authorization.substring(7);
        }
        return null;
    }
}
